package com.ftg.learn.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ftg.learn.bus.entity.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @author Guo
 * @date 2022/3/13
 */
@Slf4j
public class JWTUtil {
    /**
     * 过期时间
     */
    private static final long EXPIRE = 1000 * 60 * 60 * 24 * 7;
//    private static final long EXPIRE = 1000 * 30;
    /**
     * 加密的密钥
     */
    private static final String SECRET = "guoguo";
    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "gbt";
    /**
     * 颁布者
     */
    private static final String SUBJET = "gbt";

    /**
     * 生成token令牌
     *
     * @param loginUser
     * @return
     */
    public static String jeneJsonWebToken(LoginUser loginUser) {
        if (loginUser == null) {
            throw new NullPointerException("loginUser为空");
        }
        //构建token
        String jwt = Jwts.builder()
                .setSubject(SUBJET)
                .claim("id", loginUser.getId())
                .claim("name", loginUser.getName())
                .claim("ip", loginUser.getIp())
                //发布时间
                .setIssuedAt(new Date())
                //过期时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                //加密类型
                .signWith(SignatureAlgorithm.HS384, SECRET)
                //构建
                .compact();
        jwt = TOKEN_PREFIX + jwt;
        return jwt;
    }


    /**
     * 校验token 是否过期
     *
     * @param token
     * @return
     */
    public static Claims checkToken(String token) {
        try {
            return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
        } catch (Exception e) {
            log.error("解密失败");
            return null;
        }
    }

    /**
     * 响应JSON数据给前端
     *
     * @param response
     * @param obj
     */
    public static void sendJsonMessage(HttpServletResponse response, Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.println(mapper.writeValueAsString(obj));
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("响应JSON数据给前端异常：{}", e);
        }
    }

    public static void main(String[] args) {
//        LoginUser loginUser = LoginUser.builder()
//                .id(1L)
//                .name("郭柄彤")
//                .ip("123456").build();
//        String jsonWebToken = jeneJsonWebToken(loginUser);
//        log.info("token:{}", jsonWebToken);
        Claims claims = checkToken("wsdsbeyJhbGciOiJIUzM4NCJ9.eyJzdWIiOiJnYnQiLCJpZCI6MSwibmFtZSI6IuWkp-WRsuiKsSIsImlwIjoiMTI3LjAuMC4xIiwiaWF0IjoxNjQ3MjE3MTYwLCJleHAiOjE2NDc4MjE5NjB9.q6OfJK-Zrn36dZoPOwppxFR6ynJzEm688567fF4j0X8e4MyL7El02rYwWZi3n1j-");
//        Claims claims = checkToken("hdzzeyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJMSVVaRSIsImlkIjoxLCJuYW1lIjoibGl1emUiLCJpcCI6InVzZXItc2VydmljZTpjYXB0Y2hhOjVFMEZCNzNFQzYzMzhFNEIzRTY0NDAxMkM5QUNBRjQwIiwic2V4IjowLCJzaG9wSWQiOjEsImlhdCI6MTY0NzE1MTI4MCwiZXhwIjoxNjQ3NzU2MDgwfQ.bAiaebzF0zsydUARfvmlrZCW_zDe6iJvifVSl0ibhUQ");
        System.out.println(claims);
    }
}
